package com.crscd.jdbc.basic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 10/18/25 5:02 PM
 * @modifiedBy:
 * @version: 1.0
 */
public class JDBCprepared {
  public static void main(String[] args) throws SQLException {
    // 1.注册驱动 (从JDK6开始，不用显式的调用Class.forName()来加载JDBC驱动，只要在类路径中集成了对应的jar文件，会自动在初始化时注册驱动程序)

    // 2.获取连接对象
    String url = "jdbc:mysql://localhost:3306/testdb";
    String username = "root";
    String passwd = "Crscd123@";
    Connection connection = DriverManager.getConnection(url, username, passwd);
    // 3.获取执行SQL语句的对象
    final String sql = "select emp_id, emp_name, emp_salary, emp_age from t_emp where emp_name=?";
    PreparedStatement statement = connection.prepareStatement(sql);

    System.out.println("请输入员工姓名：");
    Scanner scanner = new Scanner(System.in);
    String name = scanner.nextLine();

    // 4.编写SQL语句，并执行，接受返回的结果集
      // 设置参数，这里防止sql注入，是在加载变量值的时候， 会将符号进行转译
    statement.setString(1, name);
    ResultSet resultSet = statement.executeQuery(sql);

    // 5.处理结果，遍历resultSet结果集
    while (resultSet.next()) {
      final int empId = resultSet.getInt("emp_id");
      final String empName = resultSet.getString("emp_name");
      final double empSalary = resultSet.getDouble("emp_salary");
      final int empAge = resultSet.getInt("emp_age");
      System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
    }
    // 6.释放资源(先开后闭)
    resultSet.close();
    statement.close();
    connection.close();
  }
}
